import * as qiniu from './qiniu.min';
// eslint-disable-next-line import/no-cycle
import { getVideoDuration } from './core';

function getFileKey(file, bType) {
    // 获取视频格式，没有就默认为mp4
    const fileType = file.type || '';
    const type = fileType.split('/')[1] || 'mp4';
    // 8位日期_业务名_毫秒时间戳+2位随机数
    const timestamp = Date.now();
    const random2 = Math.random()
        .toString()
        .slice(-2);
    const envT = window.location.hostname.startsWith('t.') ? 'test' : '';
    const key = `${WPT.Util.formatDate('Ymd', Math.floor(timestamp / 1000))}_${bType}${envT}_${timestamp}${random2}`;

    return `${key}.${type}`;
}

function getToken() {
    return new Promise(resolve => {
        const tokenUrl = WPT.Util.handleApi('/v1.0/qiniu/upload-token-l', { useEnv: true });
        WPT.getData(tokenUrl, res => {
            res.code == 0 && resolve(res.data.uptoken);
        });
    });
}

export function uploadVideo(option = { bType: 'sale' }) {
    const input = document.createElement('input');
    const isSafari = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent); // 判断当前浏览器是否为safari
    if (isSafari && WPT.os.pc) {
        input.accept = 'video/mp4,video/x-m4v,video/*';
    } else {
        input.accept = 'video/*';
    }
    input.type = 'file';
    input.style.cssText += `
        ;position: fixed;
        top: -9999px;
        left: 0;
        height: 1px;
        width: 1px;
    `;

    document.body.appendChild(input);

    input.addEventListener('change', async () => {
        const file = input.files[0];
        document.body.removeChild(input);

        option.onStart && option.onStart();
        if (file) {
            const token = await getToken();
            const observable = qiniu.upload(file, getFileKey(file, option.bType), token);
            observable.subscribe(
                data => {
                    option.onProgress && option.onProgress(parseInt(data.total.percent));
                },
                error => {
                    option.onFail && option.onFail(error);
                    // 错误上报
                    window.reportError({
                        type: 'qiniuVideoUploaderError',
                        error,
                    });
                },
                data => {
                    const { key } = data;
                    getVideoDuration(key, duration => {
                        const src = URL.createObjectURL(file);
                        option.onSuccess
                            && option.onSuccess(key, {
                                src,
                                duration,
                            });
                    });
                }
            );
        }
    });

    input.click();
}

if (!WPT.uploadVideo) {
    WPT.uploadVideo = uploadVideo;
}
